package org.ihelpuoo.io;

import java.io.IOException;
import java.io.Reader;

public class BOBReader extends Reader
{

	public BOBReader(Reader r, int c)
	{
		this.r = new PreReader(this,r,c);
	}

	private Reader	r;

	@Override
	public void close() throws IOException
	{
		r.close();
	}

	@Override
	public int read(char[] cbuf, int off, int len) throws IOException
	{
		return r.read(cbuf,off,len);
	}

	private class PreReader extends Reader
	{
		private PreReader(BOBReader parent, Reader r, int c)
		{
			this.parent = parent;
			this.c = c;
			this.r = r;
		}

		private BOBReader	parent;
		private int			c;
		private Reader		r;

		@Override
		public void close() throws IOException
		{
			r.close();
		}

		@Override
		public int read() throws IOException
		{
			parent.r = this.r;
			return c;
		}

		@Override
		public int read(char[] cbuf, int off, int len) throws IOException
		{
			if (off == 0 && len == 1)
			{
				cbuf[0] = (char)c;
				parent.r = this.r;
				return 1;
			}
			cbuf[off] = (char)c;
			int re = r.read(cbuf,off + 1,len - 1);
			parent.r = r;
			return re + 1;
		}

	}
}
